//
//  HMEmoticonManager.swift
//  04-表情键盘
//
//  Created by Admin on 16/9/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 表情包 Emoticons.bundle 的路径
let bundlePath = Bundle.main.path(forResource: "Emoticons", ofType: "bundle")!

class HMEmoticonManager: NSObject {
    static let shared: HMEmoticonManager = HMEmoticonManager()
    
    /// 最近表情模型归档的路径
    private let recentEmoticonPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! + "/recentEmoticons.plist"
    
    /// 所有表情包模型
    lazy var packages: [HMEmoticonPackageModel] = self.loadPackages()
    
    /// 加载所有的表情包
    private func loadPackages() -> [HMEmoticonPackageModel] {
        let recentPackage = HMEmoticonPackageModel(id: "", groupName: "最近", emoticons: loadRecentEmoticons())
        return [recentPackage, loadPackage(id: "com.sina.default"), loadPackage(id: "com.apple.emoji"), loadPackage(id: "com.sina.lxh")]
    }
    
    /**
     加载表情包
     - parameter id: 表情包文件夹名称
     - returns: 表情包
     */
    private func loadPackage(id: String) -> HMEmoticonPackageModel {
        // 获取 表情包文件夹/info.plist 内容
        // info.plist的路径 = bundlePath + 表情包名称 + info.plist
        let infoPath = "\(bundlePath)/\(id)/info.plist"
        // print("infoPath: \(infoPath)")
        
        // 加载 info.plist
        let infoDict = NSDictionary(contentsOfFile: infoPath)!
        
        // 获取表情包名称,赋值给当前表情包模型
        let group_name_cn = infoDict["group_name_cn"] as! String
        
        // 获取 emoticons 数组
        let emoticonsArr = infoDict["emoticons"] as! [[String: String]]
        
        // 表情模型数组
        var emoticons = [HMEmoticonModel]()
        
        // 遍历,加载表情模型
        for dict in emoticonsArr {
            // 表情字典 转 模型, 添加到表情模型数组里面
            emoticons.append(HMEmoticonModel(id: id, dict: dict))
        }
        
        // 创建表情包模型
        let package = HMEmoticonPackageModel(id: id, groupName: group_name_cn, emoticons: emoticons)
        
        return package
    }
    
    // MARK: - 最近表情相关
    /**
     添加表情到最近表情包
     parameter emoticon: 要添加的表情模型
     */
    func addFavorate(emoticon: HMEmoticonModel) {
        // 获取最近表情
        var recentEmoticons = packages[0].pageEmoticons[0]
        
        // 判断是否有重复表情
        var repeatEmoticon: HMEmoticonModel?
        for e in recentEmoticons {
            // emoji
            if (emoticon.emoji != nil && emoticon.code == e.code) || (emoticon.chs != nil && emoticon.chs == e.chs) {
                repeatEmoticon = e
                break
            }
        }
        
//        print("是否已经存在repeatEmoticon: \(repeatEmoticon)")
        
        if let e = repeatEmoticon {
            let index = recentEmoticons.index(of: e)
            recentEmoticons.remove(at: index!)
//            print("有重复表情,删除: \(index), \(e)")
        }
        
        recentEmoticons.insert(emoticon, at: 0)
        
        // 判断是否超过20个,如果超过20,将数组最后的表情删除
        if recentEmoticons.count > HMEmoticonNumberOfPage {
            recentEmoticons.removeLast()
        }
        
        // 需要赋值回去
        packages[0].pageEmoticons[0] = recentEmoticons
//        print("最近表情2: \(packages[0].pageEmoticons[0])")
        
        saveRecentEmoticons()
    }
    
    /**
     保存最近表情
     */
    private func saveRecentEmoticons() {
//        print("NSHomeDirectory: \(NSHomeDirectory())")
//        print("保存的表情模型: \(packages[0].pageEmoticons[0])")
        NSKeyedArchiver.archiveRootObject(packages[0].pageEmoticons[0], toFile: recentEmoticonPath)
    }
    
    /**
     加载最近表情
     returns: 最近表情
     */
    private func loadRecentEmoticons() -> [HMEmoticonModel] {
        if let emoticons = NSKeyedUnarchiver.unarchiveObject(withFile: recentEmoticonPath) as? [HMEmoticonModel] {
            return emoticons
        } else {
            return [HMEmoticonModel]()
        }
    }
    
    func emoticonAttrText(withString string: String) -> NSAttributedString {
        // 获取文本中的表情字符串
        // 定义匹配方案
        let pattern = "\\[.*?\\]"
        
        // 创建正则表达式对象
        let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.dotMatchesLineSeparators)
        
        // 匹配所有符合条件的内容
        let result = regular.matches(in: string, options: [], range: NSRange(location: 0, length: string.characters.count))
        
        // 定义属性字符串
        let emoticonString = NSMutableAttributedString(string: string)
        
        let font = UIFont.systemFont(ofSize: 15)
        
        // 从后面往前面遍历
        for result in result.reversed() {
            // 获取匹配结果的第一个匹配项
            let range = result.rangeAt(0)
            
            // 截取表情字符串
            let emoticonStr = (string as NSString).substring(with: range)
            
            // 表情名称转表情模型
            if let emoticon = HMEmoticonModel.emoticonMode(withEmoticonName: emoticonStr) {
                // 表情模型转带表情图片的属性文本
                let emoticonAttr = emoticon.toAttrString(font: font)
                
                // 表情字符串替换为带表情图片的属性文本
                emoticonString.replaceCharacters(in: range, with: emoticonAttr)
            }
        }
        
        emoticonString.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: emoticonString.length))
        
        return emoticonString
    }
}
